import { Service } from 'egg';
import * as moment from 'moment';
import { TeacherSchedule, UpdateTeacherSchedule } from '../model/teacher_schedule';

export default class TacherScheduleService extends Service {
    public async getTeacherSchedules(teacherId: number): Promise<TeacherSchedule[]> {
        const teacherSchedules: any[] = [
            {
                day: 1,
                time_spans: [],
                teacher_id: teacherId,
            },
            {
                day: 2,
                time_spans: [],
                teacher_id: teacherId,
            },
            {
                day: 3,
                time_spans: [],
                teacher_id: teacherId,
            },
            {
                day: 4,
                time_spans: [],
                teacher_id: teacherId,
            },
            {
                day: 5,
                time_spans: [],
                teacher_id: teacherId,
            },
            {
                day: 6,
                time_spans: [],
                teacher_id: teacherId,
            },
            {
                day: 7,
                time_spans: [],
                teacher_id: teacherId,
            },
        ];
        const result = await this.service.db.teacherSchedule.getTeacherSchedulesByTeacherId(teacherId);
        for (const schedule of result) {
            const item = teacherSchedules[schedule.day - 1];
            item.time_spans.push({
                time_from: moment(schedule.time_from, 'HH:mm:SS').format('HH:mm'),
                time_to: moment(schedule.time_to, 'HH:mm:SS').format('HH:mm'),
            });
        }
        return teacherSchedules as TeacherSchedule[];
    }

    public async updateTeacherSchedules(teacherSchedules: UpdateTeacherSchedule[], teacherId: number) {
        const conn = await this.app.mysql.beginTransaction(); // 初始化事务
        try {
            await this.service.db.teacherSchedule.removeSchedules(teacherId, conn);
            await this.service.db.teacherSchedule.addSchedules(teacherId, teacherSchedules, conn);
            await conn.commit(); // 提交事务
        } catch (err) {
            // error, rollback
            await conn.rollback(); // 一定记得捕获异常后回滚事务！！
            throw err;
        }
    }
}
